#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        unordered_map<int, int> hash;
        int res = 0, k = 0;
        int left = 0, right = 0, n = fruits.size();
        while (right < n)
        {
            while (right < n && k <= 2)
            {
                if (++hash[fruits[right++]] == 1) k++;
            }
            res = max(right - left - 1, res);
            while (left < right && k > 2)
            {
                if (--hash[fruits[left++]] == 0) k--;
            }
        }
        res = max(right - left, res);
        return res;
    }
};